package com.example.belong.ggvideo.view;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.belong.ggvideo.R;
import com.example.belong.ggvideo.bean.VideoData;
import com.example.belong.ggvideo.util.GsonUtils;
import com.example.belong.ggvideo.util.JsonUtils;
import com.liaoinstan.springview.container.DefaultFooter;
import com.liaoinstan.springview.container.DefaultHeader;
import com.liaoinstan.springview.widget.SpringView;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;

public class MainActivity extends AppCompatActivity implements SpringView.OnFreshListener {
    private RecyclerView rv_;
    private SpringView sv_;
    private ArrayList<VideoData> videoDatas;
    private ArrayList<VideoData> showVideoData;//展示的Video
    private MyAdapter adapter;
    private int pageSize = 10;
    private int showEnd = 0;
    private int loadTime = 2 * 1000;
    private Handler handler = new MyHandle(this);
    private Random random;
    private int offset=0;


    class MyHandle extends Handler {
        private WeakReference<MainActivity> activity;

        MyHandle(MainActivity activity) {
            this.activity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            MainActivity mainActivity = activity.get();
            int what = msg.what;
            switch (what) {
                case 1://数据失败
                    Toast.makeText(mainActivity, "获取数据失败，请重试", Toast.LENGTH_SHORT)
                            .show();
                    sv_.setEnable(true);
                    break;
                case 2://加载
                    showEnd = showVideoData.size();
                    AddData();
                    sv_.onFinishFreshAndLoad();
                    sv_.setEnable(true);
                    break;
                case 3://刷新
                    showVideoData.clear();
                    showEnd = 0;
                    AddData();
                    sv_.onFinishFreshAndLoad();
                    sv_.setEnable(true);
                    break;
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (JCVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        JCVideoPlayer.releaseAllVideos();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init() {
        fullScreen(this);
        getSupportActionBar().hide();
//        addStatusViewWithColor(this,R.color.cardview_dark_background);
        findView();
        initData();
        getData();
        AddData();
        initUi();
    }

    /**
     * 添加状态栏占位视图
     *
     * @param activity
     */
    private void addStatusViewWithColor(Activity activity, int color) {
        //利用反射获取状态栏高度
        int result = 0;
        //获取状态栏高度的资源id
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content);
        View statusBarView = new View(activity);
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                result);
        statusBarView.setBackgroundColor(color);
        contentView.addView(statusBarView, lp);
    }


    /**
     * 通过设置全屏，设置状态栏透明
     */
    private void fullScreen(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                //5.x开始需要把颜色设置透明，否则导航栏会呈现系统默认的浅灰色
                Window window = activity.getWindow();
                View decorView = window.getDecorView();
                //两个 flag 要结合使用，表示让应用的主体内容占用系统状态栏的空间
                int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
                decorView.setSystemUiVisibility(option);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
                //导航栏颜色也可以正常设置
//                window.setNavigationBarColor(Color.TRANSPARENT);
            } else {
                Window window = activity.getWindow();
                WindowManager.LayoutParams attributes = window.getAttributes();
                int flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
                int flagTranslucentNavigation = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
                attributes.flags |= flagTranslucentStatus;
                window.setAttributes(attributes);
            }
        }
    }

    private void findView() {
        sv_ = findViewById(R.id.sv_);
        rv_ = findViewById(R.id.rv_);
    }

    private void initData() {
        random = new Random();
        videoDatas = new ArrayList<>();
        showVideoData = new ArrayList<>();
        adapter = new MyAdapter(this, showVideoData);
    }

    private void getData() {
        String json = JsonUtils.getJson(this, JsonUtils.FILE_NAME);
        List<VideoData> videoData = GsonUtils.instance().stringToList(json, VideoData.class);
        videoDatas.clear();
        videoDatas.addAll(videoData);
        offset = random.nextInt(videoDatas.size() - 500) % (videoDatas.size() - 500 + 1);
    }

    private void initUi() {
        sv_.setHeader(new DefaultHeader(this));
        sv_.setFooter(new DefaultFooter(this));
        sv_.setListener(this);
        rv_.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.bottom = 20;

            }
        });
        rv_.setLayoutManager(new LinearLayoutManager(this));
        rv_.setAdapter(adapter);
    }

    /**
     * 添加数据
     */
    private void AddData() {
        for (int i = 0; i < pageSize; i++) {
            showVideoData.add(videoDatas.get(i + showEnd+offset));
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onRefresh() {
        new LoadThread(3).start();
    }

    @Override
    public void onLoadmore() {
        new LoadThread(2).start();
    }


    class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
        private Context context;
        private List<VideoData> data;
        private LayoutInflater inflater;

        MyAdapter(Context context, List<VideoData> data) {
            this.context = context;
            this.data = data;
            inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
        }

        @NonNull
        @Override
        public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = inflater.inflate(R.layout.rv_item, null);
            return new MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
            VideoData videoData = data.get(position);
            Glide.with(context)
                    .load(videoData.getBgimg_url())
                    .into(holder.jcv_data.thumbImageView);
            holder.jcv_data.setUp(videoData.getVideo_url()
                    , JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL
//                    , JCVideoPlayerStandard.SCROLL_AXIS_HORIZONTAL
                    , videoData.getTitle());

            Log.e("-----", videoData.getBgimg_url() + "---");
            holder.tv_time.setText(videoData.getCreate_time());
            holder.tv_len.setText("视频时长：" + videoData.getPlay_time());
        }

        @Override
        public int getItemCount() {
            return data.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            private final JCVideoPlayerStandard jcv_data;
            private final TextView tv_title;
            private final TextView tv_time;
            private final TextView tv_len;

            public MyViewHolder(View itemView) {
                super(itemView);
                jcv_data = itemView.findViewById(R.id.jcv_data);
                tv_title = itemView.findViewById(R.id.tv_title);
                tv_time = itemView.findViewById(R.id.tv_time);
                tv_len = itemView.findViewById(R.id.tv_len);
                tv_title.setVisibility(View.GONE);
                //播放比例
//                jcv_data.widthRatio = 5;
//                jcv_data.heightRatio = 3;
            }
        }
    }

    class LoadThread extends Thread {
        private int type;//2:加载 3：刷新

        LoadThread(int type) {
            this.type = type;
        }

        @Override
        public void run() {
            super.run();
            rv_.setEnabled(false);
            try {
//                int millis = loadTime * Math.abs(random.nextInt());
//                Log.e("======",millis+"---");
                Thread.sleep(loadTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
                handler.sendEmptyMessage(1);
            }
            handler.sendEmptyMessage(type);
        }
    }

}
